<!-- 质量日报 情况说明 -->
<template>
  <div class="std-operation-rate-management">
    <el-container>
      <el-header>
        <div class="common-div-card management-header">
          <el-form :inline="true" :model="searchForm" class="management-header-form">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="searchForm.startTime"
                type="datetime"
                placeholder="开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :size="headerSize"
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="searchForm.endTime"
                type="datetime"
                placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :size="headerSize"
                style="width: 160px"
              />
            </el-form-item>
            <el-form-item label="年月日">
              <el-date-picker
                v-model="searchForm.yearMonthDay"
                style="width: 120px"
                type="day"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :size="headerSize"
              />
            </el-form-item>
            <el-form-item label="区域">
              <el-select v-model="searchForm.area" clearable style="width: 120px" :size="headerSize">
                <el-option label="一冷" value="一冷" />
                <el-option label="三冷" value="三冷" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleInsert" :size="headerSize">新增</el-button>
              <el-button type="primary" @click="handleSearch" :size="headerSize">查询</el-button>
              <el-button @click="handleReset" :size="headerSize">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main>
        <el-col>
          <el-row>
            <div style="width: 100%" class="common-div-card management-table">
              <el-table
                :data="tableData"
                border
                :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                :stripe="true"
                v-loading="tableLoading"
                :show-overflow-tooltip="true"
                ref="tableRef"
              >
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column prop="area" label="区域" width="160px" />
                <el-table-column prop="yearMonthDay" label="日期" width="160px" />
                <el-table-column prop="createTime" label="创建时间" width="240px" />
                <el-table-column prop="contentA" label="情况说明" min-width="300" />
                <el-table-column label="操作" width="160" fixed="right">
                  <template #default="scope">
                    <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-row>
          <el-row>
            <!-- 分页区域 -->
            <div class="common-div-card management-pagination">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
              />
            </div>
          </el-row>
        </el-col>
      </el-main>
    </el-container>
  </div>

  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :before-close="handleClose"
    :close-on-click-modal="false"
    ref="detailDialogRef"
    @closed="cancel"
    class="detailDialog"
  >
    <div>
      <el-form :model="dialogForm" label-width="auto" ref="dialogFormRef" :rules="rules">
        <el-form-item label="区域" prop="area">
          <el-select v-model="dialogForm.area" clearable style="width: 240px">
            <el-option label="一冷" value="一冷" />
            <el-option label="三冷" value="三冷" />
          </el-select>
        </el-form-item>

        <el-form-item label="年月日" prop="yearMonthDay">
          <el-date-picker v-model="dialogForm.yearMonthDay" type="day" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="创建时间" v-if="dialogTitle === '编辑'">
          <el-text>{{ dialogForm.createTime }}</el-text>
        </el-form-item>
        <el-form-item label="情况说明">
          <el-input v-model="dialogForm.contentA" type="textarea" :rows="4" placeholder="请输入情况说明" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="dialogFormSubmit"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessageBox } from 'element-plus';
  import { listApi } from '/@/api/report/quality/index';

  interface SearchForm {
    startTime: string;
    endTime: string;
    area: string; //区域
    yearMonthDay: string;
  }

  interface tableRow {
    dbegin: string; // 开始时间
    dend: string; // 结束时间
    idno: 0; // 编号
    area: string; //区域
    yearMonthDay: string; // 年月日
    createTime: string; // 创建时间
    contentA: string; // 情况说明
  }

  const searchForm = reactive<SearchForm>({
    startTime: '',
    endTime: '',
    area: '', //区域
    yearMonthDay: '',
  });

  const tableLoading = ref(false);
  const tableRef = ref<any>();
  const dialogVisible = ref(false);
  const dialogTitle = ref('情况说明：新增');
  const dialogFormRef = ref();
  const headerSize = ref('small');
  const viewportWidth = ref();

  const reg = /[0-9]+/;

  const rules = {
    duration: [{ required: true, pattern: reg, message: '请输入数字' }],
    area: [{ required: true, type: 'string', message: '请选择区域' }],
    yearMonthDay: [{ required: true, type: 'string', message: '请选择 日期' }],
  };

  const tableData = ref<tableRow[]>([]);
  const dialogForm = reactive<tableRow>({
    dbegin: '', // 开始时间
    dend: '', // 结束时间
    idno: 0, // 编号
    area: '', //区域（一冷、三冷）
    yearMonthDay: '', // 年月日
    createTime: '', // 创建时间
    contentA: '', // 情况说明
  });

  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });

  // 搜索方法
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchTableData();
  };

  // 重置方法
  const handleReset = () => {
    (Object.keys(searchForm) as Array<keyof SearchForm>).forEach((key) => {
      searchForm[key] = '';
    });
    pagination.currentPage = 1;
    handleSearch();
  };

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // 添加方法
  const handleInsert = () => {
    dialogTitle.value = '新增';
    dialogVisible.value = true;
  };

  // 编辑方法
  const handleEdit = (row: any) => {
    dialogTitle.value = '编辑';
    dialogVisible.value = true;
    Object.assign(dialogForm, { ...row });
  };

  // 删除方法
  const handleDelete = async (row: any) => {
    try {
      const param = {
        idno: row.idno,
      };
      await listApi.delete(param).then((res) => {
        console.log('res.data.status：' + res.data.status);
        if (res.data.status != 2000) {
          throw new Error('数据删除失败：' + res.data.message);
        }
        ElNotification({
          title: '数据删除成功：',
          message: res.data.msg ?? '',
          type: 'success',
          duration: 2000,
        });
      });
    } catch (error) {
      console.log('删除失败：' + error);
      ElMessage.error('删除失败');
    } finally {
      fetchTableData();
    }
  };

  // 详情弹窗关闭事件
  const handleClose = (done: () => void) => {
    ElMessageBox.confirm('确定要放弃当前更改吗?')
      .then(() => {
        cancel();
      })
      .catch(() => {
        // catch error
      });
  };

  // 详情弹窗取消事件
  const cancel = () => {
    dialogForm.area = '';
    dialogForm.yearMonthDay = '';
    dialogForm.createTime = '';
    dialogForm.contentA = '';
    dialogForm.dbegin = '';
    dialogForm.dend = '';
    dialogForm.idno = 0;
    dialogVisible.value = false;
    dialogFormRef.value.resetFields();
  };

  // 编辑提交
  const dialogFormSubmit = async () => {
    dialogFormRef.value
      .validate()
      .then(async () => {
        let res;
        if (dialogTitle.value === '编辑') {
          const param = {
            idno: dialogForm.idno,
            area: dialogForm.area,
            yearMonthDay: dialogForm.yearMonthDay,
            contentA: dialogForm.contentA,
          };
          res = await listApi.edit(param);
        } else {
          //新增
          const param = {
            area: dialogForm.area,
            yearMonthDay: dialogForm.yearMonthDay,
            contentA: dialogForm.contentA,
          };
          res = await listApi.insert(param);
        }
        if (res.data.status != 2000) {
          throw new Error('数据录入失败：' + (res.data.message ?? ''));
        }
        ElNotification({
          title: '数据录入成功',
          message: '',
          type: 'success',
          duration: 2000,
        });
        dialogVisible.value = false;
        fetchTableData();
      })
      .catch((error: any) => {
        dialogVisible.value = false;
        fetchTableData();
        ElNotification({
          title: '数据获取失败',
          message: error.message ?? '',
          type: 'error',
          duration: 2000,
        });
        console.error('数据录入失败:', error);
      });
  };

  const fetchTableData = async () => {
    try {
      tableLoading.value = true;
      const param = {
        dbegin: searchForm.startTime,
        dend: searchForm.endTime,
        area: searchForm.area,
        yearMonthDay: searchForm.yearMonthDay,
        pageIndex: pagination.currentPage,
        pageSize: pagination.pageSize,
      };
      await listApi.page(param).then((res) => {
        if (res.data.status != 2000) {
          throw new Error('数据获取失败：' + res.data.message);
        }
        tableData.value = res.data.data;
        pagination.total = res.data.count;
        // ElNotification({
        //   title: 'Success',
        //   message: '数据获取成功',
        //   type: 'success',
        //   duration: 2000,
        // });
      });
      tableLoading.value = false;
    } catch (error: any) {
      ElNotification({
        title: '数据获取失败',
        message: error.message ?? '',
        type: 'error',
        duration: 2000,
      });
    } finally {
      tableLoading.value = false;
    }
  };

  onMounted(() => {
    viewportWidth.value = window.innerWidth;
    headerSize.value = viewportWidth.value == 1920 ? '' : 'small';
    fetchTableData();
  });
</script>

<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  @box-shadow-hover: 0 8px 32px rgba(0, 0, 0, 0.12);
  @border:1px solid #dcdfe6;

  .std-operation-rate-management {
    background-color: #fff;
  }

  .common-div-card {
    box-shadow: @box-shadow;
    transition: 0.3s;
    border-radius: @border-radius;
    border: @border;

    // 悬停状态
    &:hover {
      box-shadow: @box-shadow-hover;
    }
  }

  .management-header {
    display: flex;
    flex: 1;
    justify-content: flex-start;
    align-items: center;
    padding: 20px;
    height: 10vh;
  }

  .management-header-form {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .management-table {
    width: 100%;
    height: 70vh;
    padding: 20px;
    margin-top: 2vh;

    .el-table {
      height: calc(70vh - 40px);
    }
  }

  .management-pagination {
    width: 100%;
    height: 6vh;
    margin-top: 1vh;
    display: flex;
    justify-content: flex-end;
    padding: 20px;
  }
</style>
